import pandas as pd
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QApplication, QFileDialog, QVBoxLayout, QWidget


class ExportExcelDialog(QWidget):
    def __init__(self, list_data):
        super().__init__()
        self.model = None
        self.file_dialog = None
        self.list_data = list_data
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("导出数据")

        # 创建文件对话框
        self.file_dialog = QFileDialog(self)
        self.file_dialog.setAcceptMode(QFileDialog.AcceptSave)
        self.file_dialog.setDefaultSuffix("xlsx")
        self.file_dialog.setWindowTitle("导出")
        self.file_dialog.setDirectory(QApplication.instance().applicationDirPath())

        # 创建表格模型
        self.model = QStandardItemModel()
        for index1, row in enumerate(self.list_data):
            for index3, item in enumerate(row):
                self.model.setItem(index1, index3, QStandardItem(str(item)))

        # 创建表格布局并设置模型
        table_layout = QVBoxLayout()
        table_view = QWidget()
        # table_view.setModel(self.model)
        table_layout.addWidget(table_view)

        # 显示文件对话框并导出数据
        if self.file_dialog.exec_():
            file_path = self.file_dialog.selectedFiles()[0]
            with pd.ExcelWriter(file_path) as writer:
                df = pd.DataFrame(self.list_data)
                df.to_excel(writer, index=False, header=False)
                print(f"Excel file exported to: {file_path}")


if __name__ == "__main__":
    data = [
        ["Name", "Age", "Gender"],
        ["John", 25, "Male"],
        ["Jane", 30, "Female"],
        ["Tom", 28, "Male"]
    ]
    app = QApplication([])
    window = ExportExcelDialog(data)
